//
//  PreviewController.m
//  Collection
//
//  Created by Neelam Shehzadi on 10/3/11.
//  Copyright 2011 Confiz Solution. All rights reserved.
//

#import "PreviewController.h"
#import "dbFunctions.h"


@implementation PreviewController
@synthesize arrImgName,arrImges;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
	[arrImgName release];
	[arrImges release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


-(id)initWithImages:(NSArray*)imgArray andImagesName:(NSArray*)nameArray;
{
	arrImges = [imgArray copy];
	arrImgName = [nameArray copy];
	return self;

}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    cache = [NSUserDefaults standardUserDefaults];
    
    self.navigationItem.title = @"Preview";
    
    UIBarButtonItem *settingNavigationItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(buttonPreviewAction)];
    [self.navigationItem setRightBarButtonItem:settingNavigationItem];
    [settingNavigationItem release];
    
	[contact setText:[cache valueForKey:@"contactName"]];
	 NSLog(@"%@",[cache valueForKey:@"contactName"]);
	[dateVal setText:[cache valueForKey:@"date"]];
	[phoneVal setText:[cache valueForKey:@"phone"]];
	[timeVal setText:[cache valueForKey:@"time"]];
	[addressVal1 setText:[cache valueForKey:@"address1"]];
	[addressVal2 setText:[cache valueForKey:@"address2"]];

	[townVal setText:[cache valueForKey:@"town"]];
	[countryVal setText:[cache valueForKey:@"country"]];
	[postCodeVal setText:[cache valueForKey:@"postCode"]];
	[driverName setText:[cache valueForKey:@"driverName"]];
	[timeOutVal setText:[cache valueForKey:@"timeOut"]];
	[timeBackVal setText:[cache valueForKey:@"timeBack"]];
	[jobNoVal setText:[cache valueForKey:@"jobNo"]];
	[mileageVal setText:[cache valueForKey:@"mileage"]];
	[vehicleManufacturerVal setText:[cache valueForKey:@"vehicleManufacturer"]];
	[modelVehicleVal setText:[cache valueForKey:@"Model"]];
	[regVahicleVal setText:[cache valueForKey:@"reg"]];
	[colorVehicleVal setText:[cache valueForKey:@"color"]];
    [mileageVahicleVal setText:[cache valueForKey:@"vehicleMileage"]];
	[unableCheckVal setText:[cache valueForKey:@"unableCheckVehicle"]];
	[typeVehicleValetVal setText:[cache valueForKey:@"vechicleTypeWithVAT"]];
	[typeVehicleVal setText:[cache valueForKey:@"vehicleType"]];
	
	NSLog(@"Additional comment5%@",[cache valueForKey:@"additionalComment"]);
	
    [additionalCommentVal setText:[cache valueForKey:@"additionalComment"]];
	NSLog(@"Additional comment%@",additionalCommentVal.text);

	[areaOfDemageVal setText:[cache valueForKey:@"areaOfDemage"]];
	[fuelVahicleVal setText:[cache valueForKey:@"fuelLevel"]];
	[carVahicleVal setText:[cache valueForKey:@"carSupplied"]];
	[radioVahicleVal setText:[cache valueForKey:@"radioCode"]];
	[alarmVahicleVal setText:[cache valueForKey:@"alarm"]];
	[keysVahicleVal setText:[cache valueForKey:@"keys"]];
	[toolsVahicleVal setText:[cache valueForKey:@"tools"]];
	[wheelVahicleVal setText:[cache valueForKey:@"wheelTrims"]];
	[recoveryVahicleVal setText:[cache valueForKey:@"recoveryPaid"]];
	[personalVehicleVal setText:[cache valueForKey:@"personalItems"]];
	[drvableVahicleVal setText:[cache valueForKey:@"drivable"]];
	[taxDiscVahicleVal setText:[cache valueForKey:@"taxDesc"]];

	
  
    
    customerImage.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/customer.png",NSHomeDirectory()]]];
        
    
       
    driverImage.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/driver.png",NSHomeDirectory()]]];
   
    
    
   
    

    
    objScrollView.contentSize = CGSizeMake(320,1870);
    objScrollView.alwaysBounceVertical = TRUE;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (UIImage *) imageWithView
{
    /*UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
     [view.layer renderInContext:UIGraphicsGetCurrentContext()];
     
     UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
     
     UIGraphicsEndImageContext();
     
     return img;
     
     */
	UIImage* image;// = nil;
	UIGraphicsBeginImageContext(objScrollView.contentSize);
	{
		CGPoint savedContentOffset = objScrollView.contentOffset;
		CGRect savedFrame = objScrollView.frame;
		objScrollView.contentOffset = CGPointZero;
		objScrollView.frame = CGRectMake(0, 0, objScrollView.contentSize.width,  objScrollView.contentSize.height);
		
        
    [objScrollView.layer renderInContext: UIGraphicsGetCurrentContext()];     
		image = UIGraphicsGetImageFromCurrentImageContext();
		
		objScrollView.contentOffset = savedContentOffset;
		objScrollView.frame = savedFrame;
	}
	UIGraphicsEndImageContext();
	return image;	
}


-(void)buttonPreviewAction

{
    dbFunctions *dbf = [[dbFunctions alloc]init];
    NSMutableArray *arrPics = [[dbf getCarSectionDetails] copy] ;
    [dbf release];

    NSLog(@"preview action");
    if ([MFMailComposeViewController canSendMail]){
		MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
		picker.mailComposeDelegate = self;
		[picker setSubject:@"Collection Sheet"];
        NSDate *selected=[NSDate date];
        NSDateFormatter *format = [[NSDateFormatter alloc]init];
        [format setDateFormat:@"dd/MM/YYYY"];
        [format stringFromDate:selected];
		// Set up recipients
		
	//	NSArray *toRecipients = [NSArray arrayWithObject:[appDel.dictPDF objectForKey:@"email"]]; 
		
		//NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
		
		//NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
	//	[picker setToRecipients:toRecipients];
		
		// Attach an image to the email
		
		//NSData *myData = UIImageJPEGRepresentation([self imageWithView], 1);
		//NSData *myData = [NSData dataWithContentsOfFile:path];
		//[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
		
		NSMutableString *emailBody = [NSMutableString stringWithFormat:@"<html>"
                                      "<head runat='server'>"
                                      "<title></title>"
                                      "</head>"
                                      "<body>"
                                      "<form id='form1' runat='server' style=''>"
                                   "<div style='border: 1px solid #919191; line-height: 20px; width: 810px; padding: 5px;'>"
                                      "<table   width='800px'>"
                                      "<tr>"
                                      "<td align='center' style='padding-left: 110px;'>"
                                      "<span style='color: Red; font-size: 16px;'>Collection  Sheet</span>"
                                      "</td>"
                                      "<td align='right' width='200px'>"
                                      "<b>Print Date&nbsp;:&nbsp;</b>%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr style='height: 18px;'>"
                                      "<td colspan='2'>"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "<table    width='800px'>"
                                      "<tbody style='padding-top: 10px;'>"
                                      "<tr>"
                                      "<th colspan='2' align='center'>"
                                      "Collection Details"
                                      "</th>"
                                      "</tr>"
                                      "<tr>"
                                      "<td align='center'>"
                                      "<table    width='400px'>"
                                      "<tr>"
                                      "<td >"
                                      "<b>Contact</b>"
                                      "</td>"
                                      "<td >"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Date</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Tel No.</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Time</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "</td>"
                                      "<td align='center'>"
                                      "<table    width='400px'>"
                                      "<tr>"
                                      "<td >"
                                      "<b>Address</b>"
                                      "</td>"
                                      "<td >"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Town</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Country</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Post Code</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "</td>"
                                      "</tr>"
                                      "<tr style='height: 10px;'>"
                                      "<td colspan='2'>"
                                      "</td>"
                                      "</tr>"
                                      "</tbody>"
                                      "</table>"
                                      "<table    width='800px'>"
                                      "<tr>"
                                      "<td align='center' colspan='3'>"
                                      "<b>Driver Details</b>"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td align='left'>"
                                      "<b>Driver Name </b>%@"
                                      "</td>"
                                      "<td align='left'>"
                                      "<b>Time Out</b>&nbsp;%@"
                                      "</td>"
                                      "<td align='left'>"
                                      "<b>Job No</b>&nbsp;%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td align='right'>"
                                      "</td>"
                                      "<td align='left'>"
                                      "<b>Time Back</b>&nbsp;%@"
                                      "</td>"
                                      "<td align='left'>"
                                      "<b>Milege</b>&nbsp;%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr style='height: 10px;'>"
                                      "<td colspan='2'>"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "<table    width='800px'>"
                                      "<tr>"
                                      "<td align='center' colspan='2'>"
                                      "<b>Vehicle Details</b>"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td align='left'>"
                                      "<table width='400px'>"
                                      "<tr>"
                                      "<td >"
                                      "<b>Vehicle Manufacturer</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Model</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Reg</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Colour</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Mileage</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Tax Disc</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Drivable</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Personal/ Other Items</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "</td>"
                                      "<td align='left'>"
                                      "<table    width='400px'>"
                                      "<tr>"
                                      "<td >"
                                      "<b>Recovery Paid</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Wheel Trims</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Tools</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Keys</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Alarm</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Radio Code</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>C/car Supplied</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "<tr>"
                                      "<td>"
                                      "<b>Fuel Level</b>"
                                      "</td>"
                                      "<td>"
                                      "%@"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "</td>"
                                      "</tr>"
                                      "<tr style='height: 10px;'>"
                                      "<td colspan='2'>"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "<table    width='800px'>"
                                      "<tr>"
                                      "<td align='center' colspan='4'>"
                                      "<b>VEHICLE CONDITION</b>"
                                      "</td>"
                                      "</tr>"
                                      "</table>"
                                      "<table  width='800px' border='1'>"
                                      "<tr>"
                                      "<td align='left'>"
                                      "<b>CAR PART</b>"
                                     " </td>"
                                      "<td align='left'>"
                                      "<b>ACCIDENT DAMAGE</b>"
                                     " </td>"
                                      "<td align='left'>"
                                      "<b>NON - RELATED ACC DAMAGE</b>"
                                      "</td>"
                                      "<td align='left'>"
                                      "<b>Private Quotation Area</b>"
                                      "</td>"
                                      " </tr>",[format stringFromDate:selected],contact.text,dateVal.text,phoneVal.text,timeVal.text,addressVal1.text,townVal.text,countryVal.text,postCodeVal.text,driverName.text,timeOutVal.text,jobNoVal.text,timeBackVal.text,mileageVal.text,vehicleManufacturerVal.text,modelVehicleVal.text,regVahicleVal.text,colorVehicleVal.text,mileageVal.text,taxDiscVahicleVal.text,drvableVahicleVal.text,personalVehicleVal.text,recoveryVahicleVal.text,wheelVahicleVal.text,toolsVahicleVal.text,keysVahicleVal.text,alarmVahicleVal.text,radioVahicleVal.text,carVahicleVal.text,fuelVahicleVal.text];		
		
		
		for(int i =0;i<arrPics.count;i++)
		{
				
            
                                           	
            
            NSString *carsection = [NSString stringWithFormat:@"%@",[(NSDictionary*)[arrPics objectAtIndex:i]objectForKey:@"carsection"]];
            NSString *accidentdamage = [NSString stringWithFormat:@"%@",[(NSDictionary*)[arrPics objectAtIndex:i] objectForKey:@"accidentdamage"]];
			NSString *nonrelatedaccident = [NSString stringWithFormat:@"%@",[(NSDictionary*)[arrPics objectAtIndex:i] objectForKey:@"nonrelatedaccident"]];	
            NSString *privatequotearea = [NSString stringWithFormat:@"%@",[(NSDictionary*)[arrPics objectAtIndex:i] objectForKey:@"privatequotearea"]];	
            
            [emailBody appendString:[NSString stringWithFormat:@"<tr>"
                                         "<td align='left'>"
                                         "%@"
                                         "</td>"
                                         "<td align='left'>"
                                         "%@"
                                        " </td>"
                                         "<td align='left'>"
                                         "%@"
                                         "</td>"
                                         "<td align='left'>"
                                         "%@"
                                        " </td>"
                                        "</tr>"                                      
                                          ,carsection,accidentdamage,nonrelatedaccident,privatequotearea]];
			
		}
		
					
                                     
        [emailBody appendString:[NSString stringWithFormat:@"</table><table    width='800px'>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "<b>Quote required for Private Work</b>"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "<b>Area of Damage</b> %@"
                                                               "</td>"
                                                              "</tr>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "<b>Additional Comments </b> %@"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "<b></b>"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='left'>"
                                                               "<b>Vehicle Type</b>"
                                                               "</td>"
                                                               "<td align='left'>"
                                                               "%@"
                                                              " </td>"
                                                               "<td align='left'>"
                                                               "<b>Valet Type(Including VAT)</b>"
                                                               "</td>"
                                                               "<td align='left'>"
                                                              " %@"
                                                              " </td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "<b>Unable to Check Vehicle Properly Due To:</b> %@"
                                                               "</td>"
                                                               "</tr><tr style='height: 10px;'>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                            "<b>Disclaimer - </b>We will not be held responsible for any pre-accident damage"
                                                               "if the vehicle cannot be checked correctly"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='left' colspan='4'>"
                                                               "Advise Excess to be paid either Cash - Card - NO CHEQUES"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr style='height: 10px;'>"
                                                               "<td colspan='4'>"
                                                               "</td>"
                                                               "</tr>"
                                                               "</table>"
                                                               "<table width='800px'>"
                                                               "<tr>"
                                                               "<td align='center'>"
                                                               "<b>COLLECTION SIGNATURES</b>"
                                                               "</td>"

                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='center' style='height: 60px;'>"
                                                              " &nbsp;"
                                                              " </td>"
                                                               "<td align='center' style='height: 60px;'>"
                                                               "&nbsp;"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='center'>"
                                                               "Customer"
                                                               "</td>"
                                                              
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='center' style='height: 60px;'>"
                                                               "&nbsp;"
                                                               "</td>"
                                                               "<td align='center' style='height: 60px;'>"
                                                               "&nbsp;"
                                                               "</td>"
                                                               "</tr>"
                                                               "<tr>"
                                                               "<td align='center'>"
                                                               "Driver"
                                                               "</td>"
                                                              
                                                               "</tr>"
                                                               "</table>"
                                                               "<br />"
                                                               "</div>"
                                                               "</form>"
                                                               "</body>"
                                                               "</html>",areaOfDemageVal.text,additionalCommentVal.text,typeVehicleVal.text,typeVehicleValetVal.text,unableCheckVal.text]];
		
				
				
				 
		//NSString *emailBody = [appDel.dictPDF objectForKey:@"header"];
		[picker setMessageBody:emailBody isHTML:YES];
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
		for(int i =0;i<arrPics.count;i++)
		{
			
			//UIImage *itemsimage   = [arrImges objectAtIndex:i];	
    
			NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,[(NSDictionary*)[arrPics objectAtIndex:i]objectForKey:@"carsection"]];
			NSLog(@"%@",pngFilePath);
			NSData *itemsImageData = [NSData dataWithContentsOfFile:pngFilePath];
			//Create a base64 string representation of the data using NSData+Base64
			//NSString *itemsImageBase64String = [self Base64Encode:itemsImageData];	
			
			[picker addAttachmentData:itemsImageData mimeType:@"image/jpeg" fileName:[(NSDictionary*)[arrPics objectAtIndex:i]objectForKey:@"carsection"]];
		}		
		
        NSString *CustomerSign = [NSString stringWithFormat:@"%@/customer.jpg",docDir];
        NSData *itemsImageData = [NSData dataWithContentsOfFile:CustomerSign];
        [picker addAttachmentData:itemsImageData mimeType:@"image/jpeg" fileName:@"Customer Sign"];

        NSString *DriverSign = [NSString stringWithFormat:@"%@/driver.jpg",docDir];
        itemsImageData = [NSData dataWithContentsOfFile:DriverSign];
        [picker addAttachmentData:itemsImageData mimeType:@"image/jpeg" fileName:@"Driver Sign"];
        
        [self presentModalViewController:picker animated:YES];
		[picker release];
		
	}
				 
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	
    
	
    /*feedbackMsg.hidden = NO;
     
     // Notifies users about errors associated with the interface
     
     switch (result)
     
     {
     
     case MessageComposeResultCancelled:
     
     feedbackMsg.text = @"Result: SMS sending canceled";
     
     break;
     
     case MessageComposeResultSent:
     
     feedbackMsg.text = @"Result: SMS sent";
     
     break;
     
     case MessageComposeResultFailed:
     
     feedbackMsg.text = @"Result: SMS sending failed";
     
     break;
     
     default:
     
     feedbackMsg.text = @"Result: SMS not sent";
     
     break;
     
     }
     */
	[self becomeFirstResponder];
    [self dismissModalViewControllerAnimated:YES];	
}

@end
